<template>
  <div class="DishNames">
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="dishForm" label-width="auto" inline @keyup.enter="searchFn">
        <div>
          <el-form-item label="菜品编码：">
            <pb-input v-model="dishForm.dishCode" placeholder="请输入菜品编码"></pb-input>
          </el-form-item>
          <el-form-item label="菜品名称：">
            <pb-input v-model="dishForm.dishName" placeholder="请输入菜品名称"></pb-input>
          </el-form-item>
          <el-form-item label="菜系分类：">
            <pb-select v-model="dishForm.dishCuisineAttributeId" width="200" placeholder="请选择菜系"
              keys="dishAttributeValueId" label="dishAttributeValue"
              :options="DishListData.dishCuisineAttributeIdList" />
          </el-form-item>
          <el-form-item label="原料类别：">
            <pb-select v-model="dishForm.materialCategoryAttributeId" width="200" placeholder="请选择原料类别"
              keys="dishAttributeValueId" label="dishAttributeValue"
              :options="DishListData.materialCategoryAttributeIdList" />
          </el-form-item>
        </div>
        <div class="m-gbtop">
          <el-form-item label="供餐模式：">
            <pb-check :list="priList" @change="SetpricingFn($event)"></pb-check>
          </el-form-item>
        </div>
      </el-form>
    </searchCard>
    <pb-card padding="0" height="100%">
      <div class="content-box">
        <ContentOperation>
          <pb-button size="small" plain @click="PopDetailFn('1', {})" class="Btnleft"
            v-hasPerm="'center:dishInfo:add'">+添加</pb-button>
          <pb-button size="small" plain v-hasPerm="'center:dishInfo:import'">菜品导入</pb-button>
        </ContentOperation>
        <div class="table-box flex">
          <div class="left-tree-box">
            <pb-tree :style="{ maxHeight: treeH }" :treeData="treeData" :defaultProps="treeProps"
              @nodeClick="nodeClick"></pb-tree>
          </div>
          <div class="table-right">
            <pb-table :tableData="tableData" :column="column" :bottomElement="['pb-page']">
              <template #pic="{ row }">
                <img class="Imgs" :src="row.pic ? row.pic : '/src/assets/images/404.png'" alt="">
              </template>
              <template #operation="{ row }">
                <div class="flex">
                  <div v-hasPerm="'center:dishInfo:view'">
                    <pb-button size="small" text @click="setdetailisVisibleFn(row)">查看</pb-button>
                    <p class="divider mr-2 ml-2"></p>
                  </div>
                  <div v-hasPerm="'center:dishInfo:edit'">
                    <pb-button size="small" text @click="PopDetailFn('2', row)">编辑</pb-button>
                    <p class="divider mr-2 ml-2"></p>
                  </div>
                  <div v-hasPerm="'center:dishInfo:delete'">
                    <PopconfirmButton @confirm="deleteFn(row)"></PopconfirmButton>
                  </div>
                </div>
              </template>
            </pb-table>
            <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
              @onChange="getDishList" :total="pages.total"></pb-pagination>
          </div>
        </div>
      </div>
    </pb-card>
    <!-- <pb-card height="100%" width="100%" padding="0">
      <ContentOperation>
        <pb-button size="small" plain @click="PopDetailFn('1', {})" class="Btnleft">+添加</pb-button>
        <pb-button size="small" plain>菜品导入</pb-button>
      </ContentOperation>
      <div class="flex h-100%">
        <div class="left-tree-box">
          <pb-tree class="tree" :treeData="treeData" :defaultProps="treeProps" @nodeClick="nodeClick"></pb-tree>
        </div>
        <div class="table-right">
          <pb-table :tableData="tableData" :column="column">
            <template #pic="{ row }">
              <img class="Imgs" src="../../../assets/images/404.png" alt="">
            </template>
            <template #operation="{ row }">
              <div class="flex">
                <pb-button text @click="setdetailisVisibleFn(row)">查看</pb-button>
                <p class="divider mr-2 ml-2"></p>
                <pb-button text @click="PopDetailFn('2', row)">编辑</pb-button>
                <p class="divider mr-2 ml-2"></p>
                <PopconfirmButton @confirm="deleteFn(row)"></PopconfirmButton>
              </div>
            </template>
          </pb-table>
          <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
            @onChange="getDishList" :total="pages.total"></pb-pagination>
        </div>
      </div>
    </pb-card> -->
    <pb-drawer v-model="isVisible" :title="dialogtitle == 'add' ? '新增菜品' : '编辑菜品'" :direction="'btt'" :size="'92%'"
      @cancelFn="CancelFn" @confirmFn="confirmFn" :ConfirmText="dialogtitle == 'add' ? '下一步' : '确定'">
      <div class="flex drawerFlex" v-if="isVisible">
        <div class="drawerLeft">
          <div class="flex icontext p-t5">
            <div class="icon"><pb-icon name="success" size="24" :color="'rgba(13, 150, 139, 1)'"></pb-icon>
              <div class="lines"></div>
            </div>
            <div class="text succes1">基础信息</div>
          </div>
          <div class="flex icontext">
            <div class="icon"><pb-icon name="success" size="24" :color="'rgba(13, 150, 139, 1)'"></pb-icon>
              <div class="lines"></div>
            </div>
            <div class="text succes1">菜品属性</div>
          </div>
          <div class="flex icontext">
            <div class="icon"><pb-icon name="success" size="24" :color="'rgba(13, 150, 139, 1)'"></pb-icon>
              <div class="lines"></div>
            </div>
            <div class="text succes1">菜品图片</div>
          </div>
          <div class="flex icontext">
            <div class="icon"><pb-icon name="success" size="24" :color="'rgba(13, 150, 139, 1)'"></pb-icon>
              <div class="lines"></div>
            </div>
            <div class="text succes1">工艺视频</div>
          </div>
          <div class="flex icontext">
            <div class="icon"><pb-icon name="success" size="24" :color="'rgba(13, 150, 139, 1)'"></pb-icon>
            </div>
            <div class="text succes1">烹饪方法</div>
          </div>
        </div>
        <div class="drawerRight">
          <el-form :model="AddUpdataFrom" label-width="auto" :inline="true" class="Forms" :rules="AddUpdataFormRules"
            label-position="top" ref="ruleFormRef">
            <div class="divh3 p-t5">基础信息</div>
            <div class="Line"></div>
            <div class="flex code Alignflex">
              <div><span>菜品编码：</span><span>{{ AddUpdataFrom.dishCode }}</span></div>
              <!-- <div><span>助记码：</span>
                <span>{{ AddUpdataFrom.mnemonicCode }}</span></div> -->
              <div class="Alignflex">
                <span>助记码：</span>
                <el-form-item label="" prop="mnemonicCode" style="min-width: 120px;">
                  <div v-if="!innerVisible">
                    <span>
                      {{ AddUpdataFrom.mnemonicCode }}
                    </span>
                    <pb-icon name="edit" v-show="AddUpdataFrom.mnemonicCode" color="rgba(0,0,0,0.25)" class="ml-2"
                      @click="innerVisible = true"></pb-icon>
                  </div>
                  <pb-input v-model.trim="AddUpdataFrom.mnemonicCode" maxlength="50" v-else
                    @blur="CheckMnemonic"></pb-input>

                </el-form-item>
              </div>
            </div>
            <div class="flex dataform">
              <el-form-item label="菜品名称" prop="dishName">
                <pb-input v-model="AddUpdataFrom.dishName" placeholder="请输入菜品名称" :width="'533px'" @blur="checkNameFn"
                  :maxlength="20" />
              </el-form-item>
              <el-form-item label="菜品分类" prop="dishTypeCode">
                <pb-select v-model="AddUpdataFrom.dishTypeCode" width="533" placeholder="请选择菜品分类" keys="dishTypeCode"
                  label="dishTypeName" :options="DishListData.dishTypeCodeList" @change="getDishCodefn" />
              </el-form-item>
              <el-form-item label="份重·g(熟)">
                <pb-input v-model="AddUpdataFrom.dishWeight" placeholder="请输入份重" :width="'533px'" type="number" />
              </el-form-item>
            </div>
            <div class="divh3 m-gbtm">菜品属性</div>
            <div class="Line"></div>
            <div class="flex dataform">
              <el-form-item label="技法">
                <pb-select v-model="AddUpdataFrom.skillAttributeId" width="533" placeholder="请选择技法"
                  keys="dishAttributeValueId" label="dishAttributeValue" :options="DishListData.skillAttributeIdList" />
              </el-form-item>
              <el-form-item label="口味">
                <pb-select v-model="AddUpdataFrom.tasteAttributeId" width="533" placeholder="请选择口味"
                  keys="dishAttributeValueId" label="dishAttributeValue" :options="DishListData.tasteAttributeIdList" />
              </el-form-item>
              <el-form-item label="供餐模式">
                <pb-select v-model="AddUpdataFrom.useScopeAttributeId" width="533" placeholder="请选择供餐模式"
                  keys="dishAttributeValueId" label="dishAttributeValue" :options="DishListData.useScopeAttributeIdList"
                  @change="checkNameFn" />
              </el-form-item>
            </div>
            <div class="flex dataform">
              <el-form-item label="标签">
                <pb-select v-model="AddUpdataFrom.dishTargetAttributeIds" width="533" placeholder="请选择标签"
                  keys="dishAttributeValueId" label="dishAttributeValue" multiple
                  :options="DishListData.targetAttributeIdList" />
              </el-form-item>
              <el-form-item label="原料类别">
                <pb-select v-model="AddUpdataFrom.materialCategoryAttributeId" width="533" placeholder="请选择原料类别"
                  keys="dishAttributeValueId" label="dishAttributeValue"
                  :options="DishListData.materialCategoryAttributeIdList" />
              </el-form-item>
              <el-form-item label="菜系分类">
                <pb-select v-model="AddUpdataFrom.dishCuisineAttributeId" width="533" placeholder="请选择菜系分类"
                  keys="dishAttributeValueId" label="dishAttributeValue"
                  :options="DishListData.dishCuisineAttributeIdList" />
              </el-form-item>
            </div>
            <div class="divh3">菜品图片</div>
            <div class=" flex upload">
              <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false"
                :on-change="handleFileChange1" accept="image/*, .dng, .DNG">
                <pb-icon name="tianjia" size="36" :color="'rgba(0, 0, 0, 0.45)'"></pb-icon>
              </el-upload>
              <div class="img-container">
                <img :src="dishImg" class="dishImgs" alt="" v-if="dishImg && dishImg !== ''">
                <pb-icon name="close" color="#fff" size="24" class="delete-btn" @click="deleteImgFn"></pb-icon>
              </div>
            </div>
            <div class="uploadtext">上传食材图片，单个图片不超过10M。</div>
            <div class="divh3">工艺视频</div>
            <div class="flex upload">
              <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false"
                :on-change="handleFileChange2" accept="video/mp4,video/ogg,video/webm">
                <pb-icon name="tianjia" size="36" :color="'rgba(0, 0, 0, 0.45)'"></pb-icon>
              </el-upload>
              <div class="img-container">
                <Videos class="m-l4" v-show="dishVideoSrc && dishVideoSrc != ''" :videoSrc="dishVideoSrc" width="100"
                  height="100">
                </Videos>
                <pb-icon name="close" color="#fff" size="24" class="delete-btn" @click="deleteVideoFn"></pb-icon>
              </div>
            </div>
            <div class="uploadtext">上传工艺视频，单个视频不超过 500M。</div>
            <div class="divh3 m-gbtm">烹饪方法</div>
            <div class="m-gbtmbig">
              <pb-input type="textarea" v-model="AddUpdataFrom.cookingMethods" placeholder="" width="100%"
                maxlength="100" :showwordlimit="true" :autosize="{
                  minRows: 3, maxRows: 3
                }" />
              <!-- <pb-input type="textarea" v-model="AddUpdataFrom.cookingMethods" placeholder="" :width="'100%'" /> -->
            </div>
          </el-form>
        </div>
      </div>
      <div class="Line"></div>
    </pb-drawer>
    <Deatils :detailisVisible="detailisVisible" :Bomdata="Bomdata" :Bomdetails="Bomdetails" @OffEdit="OffEdit"
      @sendedit="sendedit" v-if="detailisVisible">
    </Deatils>
    <!-- <div class="Line"></div> -->
  </div>
</template>

<script lang="ts" setup>
import { upperLetter } from "@/utils/upperLetter";
import Deatils from './details/index.vue'
import { GetFileProgressApi } from '@/api/upload'
import { getDishinfoListApi, GetDishTypeAttributeApi, getDishTypeApi, AddDishApi, GetDishTypeValueListApi, getDishClassListApi, GetGeneratedishCodeApi, editDishApi, deleteDishApi, GttDishBomDetalApi, GetCheckNameApi } from '@/api/Dashmana'
import type { FormInstance } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { showLoading, hideLoading } from '@/utils/loading';
import { useRouter } from 'vue-router';

const router = useRouter();
const checkNameFn = () => {
  GetCheckNameApi({
    "dishId": dialogtitle.value == 'add' ? 0 : AddUpdataFrom.dishId,
    "dishName": AddUpdataFrom.dishName,
    "useScopeAttributeId": AddUpdataFrom.useScopeAttributeId
  }).then((res: any) => {
    if (res.data.dishNameExist) {
      AddUpdataFormRules.value.dishName.push({
        validator: (rule, value, callback) => {
          callback(new Error('菜品名称不能重复！'));
        },
        trigger: 'blur',
        required: false
      });
    } else {
      if (AddUpdataFormRules.value.dishName.length > 1) {
        AddUpdataFormRules.value.dishName.length = 1
      }
    }
  })
}
const innerVisible = ref(false)
const CheckMnemonic = (val) => {
  let reg = /^(?![0-9]+$)[A-Z0-9]{1,10}$/
  if (reg.test(val)) {
    innerVisible.value = false
  }
}
const dishForm = reactive({
  dishCode: '',
  dishName: '',
  dishCuisineAttributeId: '',
  materialCategoryAttributeId: '',
  useScopeAttributeId: null,
  dishTypeCode: ''
})
const Bomdata = reactive({

} as any)
const Bomdetails = ref({} as any)
const pages = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const AddUpdataFrom = reactive({
  dishCode: '',
  dishName: '',
  dishTypeCode: '',
  dishWeight: '',
  skillAttributeId: '',
  tasteAttributeId: '',
  useScopeAttributeId: '',
  materialCategoryAttributeId: '',
  dishTargetAttributeIds: [],
  dishCuisineAttributeId: '',
  cookingMethods: '',
  mnemonicCode: ''
} as any)
const priList = ref([{
  label: '全部',
  val: '',
}] as any)
const detailisVisible = ref(false)
const sendedit = () => {
  detailisVisible.value = false
}
const OffEdit = () => {
  detailisVisible.value = false
}
const SetpricingFn = (el: any) => {
  dishForm.useScopeAttributeId = el.val
  getDishList()
}
const setdetailisVisibleFn = (row: any) => {
  // console.log(row, '11')
  Bomdata.dishName = row.dishName
  Bomdata.dishId = row.dishId
  Bomdata.dishCode = row.dishCode
  GttDishBomDetalApi({ dishCode: row.dishCode }).then((res: any) => {
    Bomdetails.value = res.data
  })
  detailisVisible.value = true;

}
const treeProps = { children: "children", label: "dishTypeName" };
const treeData = ref([] as any)
let treeH = ref(null)
const getNodeDishType = () => {
  treeData.value.length = 0
  getDishTypeApi({
    type: 'weight'
  }).then(res => {
    treeData.value.push({
      dishTypeCode: '',
      dishTypeName: '全部',
      children: res.data
    })
    getDishList()
    // dishForm.dishTypeCode = '01'
    var height = document.getElementsByClassName("pb-table");
    treeH.value = height[0].offsetHeight + "px";

    window.addEventListener("resize", () => {
      height = document.getElementsByClassName("pb-table");

      treeH.value = height[0].offsetHeight + "px";
    });
  })
}
const nodeClick = (data: any) => {
  console.log(data.curNode)
  dishForm.dishTypeCode = data.curNode.dishTypeCode
  getDishList()
};
watch(
  () => [AddUpdataFrom.dishName,],
  ([newName]) => {
    // let name = newName ? upperLetter(newName) : ''
    AddUpdataFrom.mnemonicCode = newName ? upperLetter(newName) : ''
  }
)
const deleteFn = (row: any) => {
  deleteDishApi({ dishId: row.dishId }).then((res: any) => {
    if (res.code == 2000) {
      getDishList()
    }
  })
}
const clearObjKey = (clearForm: any) => {
  Object.keys(clearForm).forEach((key: any) => {
    if (Array.isArray(clearForm[key])) {
      // 如果属性是数组，则清空数组
      clearForm[key].length = 0;
    } else {
      // 如果属性不是数组，则设置为默认值（默认为空字符串）
      clearForm[key] = '';
    }
  });
}
const getDishCodefn = (el: any, ta: any) => {
  GetGeneratedishCodeApi({
    "dishTypeCode": el[0].dishTypeCode
  }).then((res: any) => {
    console.log(res, '1')
    AddUpdataFrom.dishCode = res.data.dishCode
  })
}
const DishListData = reactive({
  skillAttributeIdList: [],
  tasteAttributeIdList: [],
  useScopeAttributeIdList: [],
  targetAttributeIdList: [],
  materialCategoryAttributeIdList: [],
  dishCuisineAttributeIdList: [],
  dishTypeCodeList: []
} as any)
const checkList = ref([] as any)
const handleClick = (tab: any, event: Event) => {
  console.log(tab, event)
}
const tableData = ref([])

const validateName = (rule, value, callback) => {
  const title = /^[\u4e00-\u9fa5]{1,}$/;
  if (!value) return callback(new Error("请输入名称"));
  const regex = /^[A-Za-z0-9\u4e00-\u9fa5]+$/;
  if (!regex.test(value)) {
    return callback(new Error('只允许输入中文、英文、数字'));
  }
  else {
    callback();
  }
}
const AddUpdataFormRules = ref({
  dishName: [
    { required: true, validator: validateName, trigger: 'blur' }
  ],
  dishTypeCode: [
    { required: true, message: '请选择菜品分类', trigger: 'change' },
  ],
  mnemonicCode: [{ pattern: /[A-Z0-9]{1,50}$/, message: "必须为大写字母或数字", trigger: ["blur", "change"] },]
})
const column = [{
  name: '图片',
  slot: 'pic',
  width: 50,
},
{
  key: 'dishCode',
  name: '菜品编码',
  width: 60,
  align: "right",
},
{
  key: 'dishName',
  name: '菜品名称',
  width: 60,

},
{
  key: 'dishTypeName',
  name: '菜品分类',
  width: 60,

},
{
  key: 'skill',
  name: '技法',
  width: 60,

},
{
  key: 'materialCategory',
  name: '原料类别',
  width: 60,

},
{
  key: 'dishUseScopeName',
  name: '供餐模式',
  width: 50,

},
{
  key: 'dishCuisine',
  name: '菜系分类',
  width: 50,

},
{
  key: 'dataSource',
  name: '来源',
  width: 50,

},
{
  slot: 'operation',
  name: '操作',
}]

const PopDetailFn = (Tnums: string, row: {}) => {
  clearObjKey(AddUpdataFrom)
  dishImg.value = ''
  dishVideoSrc.value = ''
  DishListData.useScopeAttributeIdList[0].dishAttributeValueId ? AddUpdataFrom.useScopeAttributeId = DishListData.useScopeAttributeIdList[0].dishAttributeValueId : ''
  // clearObjKey(DishListData)
  if (Tnums == '1') {
    AddUpdataFrom.dishTargetAttributeIds = []
    dialogtitle.value = 'add'
  } else {
    Object.assign(AddUpdataFrom, JSON.parse(JSON.stringify(row)))
    dishImg.value = JSON.parse(JSON.stringify(row)).pic
    dishVideoSrc.value = JSON.parse(JSON.stringify(row)).video
    dialogtitle.value = 'update'
  }
  isVisible.value = true
}
const isVisible = ref(false)
const dialogtitle = ref('')
const searchFn = () => {
  getDishList()
}
const resetFn = () => {
  clearObjKey(dishForm)
  dishForm.useScopeAttributeId = null
  priList.value.map(el => {
    el.checked = false
  })
  priList.value[0].checked = true
  getDishList()
}
const handleAvatarSuccess = () => {

}
const dishImg = ref('')
const dishVideoSrc = ref('')
const selectedFile1 = ref<File | null>(null);
const selectedFile2 = ref<File | null>(null);
// 文件选择变化时的处理函数
const handleFileChange1 = (file: File) => {
  // 允许的文件类型
  const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/x-adobe-dng', 'image/webp'];
  // 允许的文件扩展名
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.dng', '.DNG', '.webp'];

  // 允许的最大文件大小，单位为字节，10MB = 10 * 1024 * 1024 字节
  const maxSize = 10 * 1024 * 1024;

  // 检查文件类型是否符合要求
  const isAllowedType = allowedMimeTypes.includes(file.type) || allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
  // 检查文件大小是否符合要求
  const isAllowedSize = file.size <= maxSize;

  if (isAllowedType && isAllowedSize) {
    selectedFile1.value = file;
    // 手动触发上传
    if (selectedFile1.value) {
      uploadFile1(selectedFile1.value);
    }
  } else {
    if (!isAllowedType) {
      createMessage({
        message: '不支持的文件格式，请上传图片文件。',
        type: 'error'
      })
    }
    if (!isAllowedSize) {
      createMessage({
        message: '文件大小超过限制，最大允许 10MB。',
        type: 'error'
      })
    }
  }
};

// 上传文件的函数
const uploadFile1 = async (file: any) => {
  const formData = new FormData();
  formData.append('file', file.raw);
  GetFileProgressApi(formData).then(res => {
    if (res.code == 2000) {
      dishImg.value = res.data.fileUrl
    }
  })
};

const handleFileChange2 = (file: File) => {
  const allowedMimeTypes = ['video/mp4'];
  // 允许的文件扩展名
  const allowedExtensions = ['.mp4'];
  // 允许的最大文件大小，单位为字节，500MB = 500 * 1024 * 1024 字节
  const maxSize = 500 * 1024 * 1024;

  // 检查文件类型是否符合要求
  const isAllowedType = allowedMimeTypes.includes(file.type) || allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
  // 检查文件大小是否符合要求
  const isAllowedSize = file.size <= maxSize;

  if (isAllowedType && isAllowedSize) {
    selectedFile2.value = file;
    // 手动触发上传
    if (selectedFile2.value) {
      uploadFile2(selectedFile2.value);
    }
  } else {
    if (!isAllowedType) {
      createMessage({
        message: '不支持的文件格式，请上传视频文件。',
        type: 'error'
      })
    }
    if (!isAllowedSize) {
      createMessage({
        message: '文件大小超过限制，最大允许 500MB。',
        type: 'error'
      })
    }
  }
};
const uploadFile2 = async (file: any) => {
  const formData = new FormData();
  formData.append('file', file.raw);
  GetFileProgressApi(formData).then(res => {
    if (res.code == 2000) {
      dishVideoSrc.value = res.data.fileUrl
    }
  })
};
const deleteImgFn = () => {
  dishImg.value = ''
}
const deleteVideoFn = () => {
  dishVideoSrc.value = ''
}
const getDishList = () => {
  getDishinfoListApi({
    "currentPage": pages.currentPage,
    "pageSize": pages.pageSize,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "dishCode": dishForm.dishCode,
    "dishName": dishForm.dishName,
    "dishCuisineAttributeId": dishForm.dishCuisineAttributeId,
    "useScopeAttributeId": dishForm.useScopeAttributeId,
    "materialCategoryAttributeId": dishForm.materialCategoryAttributeId,
    "dishTypeCode": dishForm.dishTypeCode
  }).then((res: any) => {
    tableData.value = res.data.records
    pages.total = res.data.total
  })
}
const initfn = () => {
  GetDishTypeAttributeApi({}).then((res: any) => {
    checkList.value = res.data
  })
  GetDishTypeValueListApi({
    "currentPage": 0,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "dishAttributeType": ""
  }).then((res) => {
    res.data.records.forEach((el: any) => {
      if (el.enableState) {
        if (el.dishAttributeType == 'skill') {
          DishListData.skillAttributeIdList.push(el)
        } else if (el.dishAttributeType == 'taste') {
          DishListData.tasteAttributeIdList.push(el)
        } else if (el.dishAttributeType == 'scope') {
          priList.value.push({
            label: el.dishAttributeValue,
            val: el.dishAttributeValueId,
            checked: false
          })
          DishListData.useScopeAttributeIdList.push(el)
        } else if (el.dishAttributeType == 'target') {
          DishListData.targetAttributeIdList.push(el)
        } else if (el.dishAttributeType == 'material') {
          DishListData.materialCategoryAttributeIdList.push(el)
        } else if (el.dishAttributeType == 'cuisine') {
          DishListData.dishCuisineAttributeIdList.push(el)
        }
      }
    })
    priList.value[0].checked = true
  })
  getDishClassListApi({
    "currentPage": 1,
    "pageSize": -1,
    "parentDishTypeCode": "",
    type: null,
    "dishTypeLevel": 2
  }).then(res => {
    DishListData.dishTypeCodeList = res.data.records
  })
}
const CancelFn = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields(); // 重置表单并清除校验规则
  }
  isVisible.value = false
}
const confirmFn = async () => {
  if (ruleFormRef.value) {
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        showLoading()
        if (dialogtitle.value == 'add') {
          AddDishApi({
            "dishCode": AddUpdataFrom.dishCode,
            "dishName": AddUpdataFrom.dishName,
            "mnemonicCode": AddUpdataFrom.mnemonicCode,
            "dishTypeCode": AddUpdataFrom.dishTypeCode,
            "dishWeight": AddUpdataFrom.dishWeight,
            "pic": dishImg.value,
            "video": dishVideoSrc.value,
            "cookingMethods": AddUpdataFrom.cookingMethods,
            "materialCategoryAttributeId": AddUpdataFrom.materialCategoryAttributeId,
            "dishCuisineAttributeId": AddUpdataFrom.dishCuisineAttributeId,
            "skillAttributeId": AddUpdataFrom.skillAttributeId,
            "tasteAttributeId": AddUpdataFrom.tasteAttributeId,
            "useScopeAttributeId": AddUpdataFrom.useScopeAttributeId,
            "dishTargetAttributeIds": (AddUpdataFrom.dishTargetAttributeIds && AddUpdataFrom.dishTargetAttributeIds.length > 0) ? AddUpdataFrom.dishTargetAttributeIds : []
          }).then((res: any) => {
            if (res.code == 2000) {
              hideLoading();
              createMessage({
                message: '添加成功'
              })
              dishForm.dishTypeCode = AddUpdataFrom.dishTypeCode
              // isVisible.value = false
              sessionStorage.setItem('dishmanageObj', JSON.stringify({
                dishId: res.data.dishId,
                dishName: res.data.dishName,
                dishCode: res.data.dishCode
              }))
              router.push({ path: '/dishbom' })
              // getDishList()
            }
          }).finally(err => {
            hideLoading();
          })
        } else {
          editDishApi({
            "dishId": AddUpdataFrom.dishId,
            "dishCode": AddUpdataFrom.dishCode,
            "dishName": AddUpdataFrom.dishName,
            "mnemonicCode": AddUpdataFrom.mnemonicCode,
            "dishTypeCode": AddUpdataFrom.dishTypeCode,
            "dishWeight": AddUpdataFrom.dishWeight,
            "pic": dishImg.value,
            "video": dishVideoSrc.value,
            "cookingMethods": AddUpdataFrom.cookingMethods,
            "materialCategoryAttributeId": AddUpdataFrom.materialCategoryAttributeId,
            "dishCuisineAttributeId": AddUpdataFrom.dishCuisineAttributeId,
            "skillAttributeId": AddUpdataFrom.skillAttributeId,
            "tasteAttributeId": AddUpdataFrom.tasteAttributeId,
            "useScopeAttributeId": AddUpdataFrom.useScopeAttributeId,
            "dishTargetAttributeIds": (AddUpdataFrom.dishTargetAttributeIds && AddUpdataFrom.dishTargetAttributeIds.length > 0) ? AddUpdataFrom.dishTargetAttributeIds : []
          }).then((res: any) => {
            if (res.code == 2000) {
              hideLoading();
              createMessage({
                message: '编辑成功'
              })
              isVisible.value = false
              getDishList()
            }
          }).finally(err => {
            hideLoading();
          })
        }
        // 提交表单
      } else {
        // 处理验证错误
      }
    });
  }
}
onMounted(() => {
  getNodeDishType()
  initfn()
})
</script>

<style lang="scss">
.DishNames {
  margin-bottom: 0;

  .el-form-item {
    margin-bottom: 0;
  }

  .el-form--inline.el-form--label-top {
    display: block;
  }

  .el-form-item--default .el-form-item__label {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    height: 24px;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
    text-align: right;
    font-style: normal;
    text-transform: none;
    // margin-bottom: 8px;
  }

  .el-textarea__inner {
    resize: none;
    height: 104px;
  }

  .el-input__inner[type="textarea"]::webkit-resizer {
    display: none;
    /* 这可能不起作用，因为伪元素的名称可能不同 */
  }

  .el-form-item__label-wrap {
    margin-left: 0 !important;
  }

  .el-upload {
    // background: rgba(0, 0, 0, 0.04);
  }
}
</style>
<style lang="scss" scoped>
.DishNames {
  .Btnleft {
    margin-right: 24px;
  }

  .Imgs {
    width: 38px;
    height: 38px;
  }

  .left-tree-box {
    width: 15.6%;
  }

  .table-right {
    flex: 1;
    padding: 16px;
    box-sizing: border-box;

    .ceshi {
      position: absolute;
      top: 0;
      left: 0;
    }
  }

  .drawerFlex {
    .drawerLeft {
      width: 7.7%;
      height: 100%;

      .icontext {
        .icon {
          display: flex;
          flex-direction: column;
          justify-content: center;
          /* 垂直居中 */
          align-items: center;

          .lines {
            width: 2px;
            height: 54px;
            background: #0D968B;
            border-radius: 0px 0px 0px 0px;
            margin: 7px 0;
          }
        }

        .text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.85);
          line-height: 22px;
          text-align: center;
          font-style: normal;
          text-transform: none;
          margin-left: 16px;
        }

        .succes1 {
          color: rgba(13, 150, 139, 1);
        }
      }
    }

    .drawerRight {
      flex: 1;
      padding-left: 24px;
      border-left: 1px solid rgba(0, 0, 0, 0.10);

      .divh3 {
        margin: 0;
        font-family: PingFang SC, PingFang SC;
        font-weight: 600;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.85);
        line-height: 24px;
        text-align: left;
        font-style: normal;
        text-transform: none;
      }

      .code {
        margin: 21px 0;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.65);
        line-height: 24px;
        text-align: right;
        font-style: normal;
        text-transform: none;

        span:nth-child(2) {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 14px;
          min-width: 60px;
          color: rgba(0, 0, 0, 0.85);
          line-height: 22px;
          text-align: right;
          font-style: normal;
          text-transform: none;
          display: inline-block;
          margin-right: 40px;
        }
      }

      .dataform {
        flex-wrap: wrap;
        margin-top: 24px;
        margin-bottom: 36px;

        >div {
          margin-right: 40px;
        }

        >div:last-child {
          margin-right: 0;
        }
      }

      .m-gbtm {
        margin-bottom: 24px;
      }

      .m-gbtmbig {
        margin-bottom: 63px;
      }

      .labels {
        .top {
          margin-bottom: 6px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.65);
          // line-height: 24px;
          font-style: normal;
          text-transform: none;
        }

        margin-bottom: 40px;
      }

      .upload {
        margin: 22px 0 6px 0;
      }

      .uploadtext {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        line-height: 22px;
        text-align: left;
        font-style: normal;
        text-transform: none;
        margin-bottom: 40px;
      }
    }
  }

  .m-gbtop {
    margin: 20px 0;
  }

  .avatar-uploader {
    width: 80px;
    justify-content: center;
    display: flex;
    height: 80px;
    background: rgba(0, 0, 0, 0.04);
  }

  .dishImgs {
    width: 100px;
    height: 100px;
    margin-left: 15px;
  }

  .Line {
    height: 1px;
    margin-top: 16px;
    width: 100%;
    background: rgba(0, 0, 0, 0.10)
  }
}

.Alignflex {
  display: flex;
  align-items: center;
}

.img-container {
  position: relative;
  display: inline-block;
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  display: none;
  /* 初始状态隐藏删除按钮 */
}

.img-container:hover .delete-btn {
  display: block;
  cursor: pointer;
  /* 鼠标悬停在容器上时显示删除按钮 */
}
</style>
